// component/goods/goods.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    goodsData: {
      type: Object,
      value: {},
      observer: function (newVal, oldVal) {
        if (newVal) {
          this.calcPrice(newVal.quantity);
        }
      }
    },
    numConstant: {
      type: Boolean,
      value: true,
    }
  },
  data: {
    price: 0,
    goods_num: 1,
  },
  methods: {
    /**
     * 减少商品数量
     */
    goods_num_reduce: function () {
      var goods_num = this.data.goods_num - 1;
      if (goods_num > 0) {
        this.calcPrice(goods_num);
      }
    },
    /**
     * 增加商品数量
     */
    goods_num_add: function () {
      var goods_num = this.data.goods_num + 1;
      if (goods_num > this.data.goodsData.stock) {
        this.setData({
          message: '超过购买上限数量'
        })
      } else {
        this.calcPrice(goods_num);
      }
    },

    /**
     * 计算价格
     */
    calcPrice: function (goods_num) {
      //如果数量固定，则显示价格为商品单价
      if (this.data.numConstant === true) {
        this.setData({
          price: parseFloat(this.data.goodsData.sell_price),
          goods_num: goods_num,
        })
        return;
      }

      goods_num = parseInt(goods_num);
      var price = parseFloat(this.data.goodsData.sell_price) * goods_num;
      price = Math.round(price * 100) / 100;

      //价格变动
      if (this.data.price) {
        var detail = {
          goods_num: goods_num,
        }
        this.triggerEvent('numChange', detail, {})
      }

      this.setData({
        price: price,
        goods_num: goods_num,
      })
    },
  }
})